<?php

namespace App\Models;

//use Illuminate\Database\Eloquent\SoftDeletes;
//use Tymon\JWTAuth\Contracts\JWTSubject;
//use Illuminate\Foundation\Auth\User as Authenticatable;
//use Illuminate\Notifications\Notifiable;

use GuzzleHttp\Client;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;
use Tymon\JWTAuth\Contracts\JWTSubject;


class User extends Authenticatable implements JWTSubject
{
    use Notifiable;
    use SoftDeletes;

    protected $table = 'users';

    /**
     * 定义主键
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * 禁止批量赋值的字段
     *
     * @var array
     */
    protected $guarded = ['id','created_at','deleted_at'];

    /**
     * 软删除应该被调整为日期的属性
     * [$dates description]
     * @var [type]
     */
    protected $dates=[
        'created_at', 'updated_at','deleted_at'
    ];

    protected $hidden = ['user_pwd'];

    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    public function getJWTCustomClaims()
    {
        return [];
    }

    public function user_address(){
        return $this->hasOne(UserAddress::class,'user_id','id');
    }

    public function reservation_service_category() {
        return $this->hasOne(ReservationServiceCategory::class, 'id', 'service_catid');
    }


    protected $appends = ['head_portrait_url'];

    public function getHeadPortraitUrlAttribute()
    {
        return config('app.img_url').$this -> head_portrait;
    }

    // 获取位置信息
    public static function getAddress($code){

        switch (strlen($code)) {
            case 2:
                // 获得省
                $query = EacooProv::query();
                $query->select('code as id','prov as name');
                break;
            case 4:
                // 获得市
                $query = EacooCity::query();
                $query->select('code as id','city as name','prov_code as pid');
                break;
            case 6:
                // 获得区
                $query = EacooCountry::query();
                $query->select('code as id','country as name','city_code as pid');
                break;
            case 9:
                // 获得镇
                // 最新的镇编号为12位，库中未更新的为9位，所以要兼容9位或者12位
            case 12:
                // 获得镇
                $query = EacooTown::query();
                $query->select('code as id','town as name','country_code as pid');

                break;
            default:
                return [];
        }

        $query->where('code', $code);
        $data = $query->first();

        return $data;
    }


    /*
     * 存储用户地址 和 身份证号
     * @param array
     * @return bool
     */
    public static function userDetailAddress($param)
    {
        $address_region = json_decode($param['address_region'],true);
        $user = user::find(auth() -> id());

        if($address_region){
            $str = '';
            foreach($address_region as $v){
                $str .= $v['name'];
            }
            $user -> address_region = $str;
        }

        $user -> real_name = $param['real_name'];
        $user -> id_num = $param['id_num'];
        $user -> sex = $param['sex'] ?? 1;
        $user -> address_detailed = $param['address_detailed'];
        return $user -> save();
    }



    /**
     * 根据父级code获得地区列表
     * @param string $parentsCode 父级别code
     * @return array|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public static function getAddressByPrentsCode($parentsCode = '')
    {
        switch (strlen($parentsCode)) {
            case 0:
                // 获得全部省
                $query = EacooProv::query();
                $query->select('code as id', 'prov as name');
                break;
            case 2:
                // 获得全部市
                $query = EacooCity::query();
                $query->select('code as id', 'city as name', 'prov_code as pid');
                $query->where('prov_code', $parentsCode);
                break;
            case 4:
                // 获得全部区
                $query = EacooCountry::query();
                $query->select('code as id', 'country as name', 'city_code as pid');
                $query->where('city_code', $parentsCode);
                break;
            case 6:
                // 获得全部乡镇
                $query = EacooTown::query();
                $query->select('code as id', 'town as name', 'country_code as pid');
                $query->where('country_code', $parentsCode);
                break;
            case 9:
                // 获得全部村委
                $query = EacooVillage::query();
                $query->select('code as id', 'village as name', 'town_code as pid');
                $query->where('town_code', $parentsCode);
                break;
            default:
                return [];
        }

        $listData = $query->get();

        // 补全省份数据中的pid
        if (strlen($parentsCode) == 0) {
            foreach ($listData as &$listDataVal) {
                $listDataVal->pid = '';
            }
        }

        return $listData;
    }


    // ip地址获取位置信息
    public static function getLocal($lng,$lat){

        $http = new Client();
        $params = [
            'output'      => 'json',
            'location'    => $lng.','.$lat,
            'key'         => config('geode.geode_key'),
            'radius'      => '1000',
            'extensions'  => 'base'
        ];

        $params = http_build_query($params);
        $url = "https://restapi.amap.com/v3/geocode/regeo?".$params;

        $res = $http ->get($url);
        return json_decode($res->getBody()->getContents(), true);
    }

    // 判断是否是乡村振兴员
    public static function isAdminVillageUser()
    {
        //乡村振兴员
        $user_id = auth() -> id();
        $user = User::find($user_id);
        if (empty($user)) {
            return false;
        }

        if($user->role == 1){
            if($adminUser = AdminUsers::where('user_id', $user_id) -> first()){
                return $adminUser;
            }
        }
        return false;

    }
}
